package com.tech.connect.zhaofuwu;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.request.RequestOptions;
import com.ksy.common.image.ImageLoader;
import com.ksy.common.image.transformations.RoundedCornersTransformation;
import com.ksy.common.utils.AndroidUtil;
import com.ksy.common.utils.BaseAdapter;
import com.ksy.common.utils.BaseHolder;
import com.ksy.common.utils.DateUtil;
import com.ksy.common.view.ProxyLayout;
import com.ksy.common.view.PullToRefreshLayout;
import com.tech.connect.R;
import com.tech.connect.api.BaseEntityOb;
import com.tech.connect.api.HttpUtils;
import com.tech.connect.api.ImageApi;
import com.tech.connect.api.QuznZiHttp;
import com.tech.connect.api.UserInfo;
import com.tech.connect.fragment.BaseFragment;
import com.tech.connect.model.ItemQuznZi;
import com.tech.connect.model.PagerModel;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class QuanZiMineFragment extends BaseFragment {

    private BaseAdapter<ItemQuznZi, BaseHolder> adapter;
    private RecyclerView recycler;
    private List<ItemQuznZi> allList = new ArrayList<>();
    private int page = 1;
    private int pageSize = 15;
    private ProxyLayout<RecyclerView> proxyLayout;
    private int height;
    private View header;
    private int currentDay;

    @Override
    protected boolean isShowHeadBar() {
        return true;
    }

    @Override
    protected boolean isFullStateBar() {
        return true;
    }

    @Override
    public View onCreateView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.layout_recycler, null);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getHeadBar().setLeftIcon(R.drawable.icon_back, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (activity != null) {
                    activity.onBackPressed();
                }
            }
        }).setTitle("服务圈").setRightText("评论", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jump2Activity(PublishQuanZiActivity.class, 996);
            }
        });
        height = AndroidUtil.dip2px(80);
        currentDay = DateUtil.getDay();
        initView(view);
        loadData();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (requestCode == 996) {
            if (Activity.RESULT_OK == resultCode) {
                page = 1;
                loadData();
            }
        } else if (requestCode == 995) {
            if (Activity.RESULT_OK == resultCode) {
                String data = intent.getStringExtra("data");
                int position = intent.getIntExtra("position", -1);
                Serializable extra = intent.getSerializableExtra("extra");
                if (position >= 0 && position < allList.size() && extra instanceof ItemQuznZi) {
                    ItemQuznZi itemQuznZi = (ItemQuznZi) extra;
                    comment(data, itemQuznZi, position);
                }
            }
        }
    }

    private void initView(View view) {
//        View rootLayout = view.findViewById(R.id.rootLayout);
        recycler = view.findViewById(R.id.recycler);
        header = LayoutInflater.from(activity).inflate(R.layout.header_quanzi_image, null);
        recycler.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return true;
            }
        });
//        recycler.addItemDecoration(new HLineDivider(Color.parseColor("#00000000"),10));
        proxyLayout = new ProxyLayout<>(activity, recycler);
        proxyLayout.setCanRefresh(true);
        proxyLayout.setDragListener(new PullToRefreshLayout.DragListener() {
            @Override
            public void drag2Upper(PullToRefreshLayout pullToRefreshLayout) {
                ++page;
                loadData();
            }

            @Override
            public void drag2Downer(PullToRefreshLayout pullToRefreshLayout) {
                page = 1;
                loadData();
            }
        });
    }


    private void initAdapter(List<ItemQuznZi> list) {
        if (list != null) {
            allList.addAll(list);
        }
        if (adapter == null) {
            adapter = new BaseAdapter<ItemQuznZi, BaseHolder>(R.layout.item_layout_quanzi_mine, allList) {
                @Override
                public int getItemViewType(int position) {
                    if (position == 0) {
                        return -1;
                    }
                    return 1;
                }

                @Override
                public int getItemCount() {
                    return allList.size() + 1;
                }

                @Override
                public BaseHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    BaseHolder baseHolder;
                    if (viewType == 1) {
                        View inflate = LayoutInflater.from(parent.getContext()).inflate(itemLayoutId, parent, false);
                        baseHolder = new BaseHolder(inflate);
                    } else {
                        baseHolder = new BaseHolder(header);
                    }
                    return baseHolder;

                }

                @Override
                protected void convert(BaseHolder helper, final int poi) {
                    if (poi == 0) {
                        View mine = helper.getView(R.id.mine);
                        mine.setVisibility(View.VISIBLE);
                        ImageView ivCover = helper.getView(R.id.ivCover);
                        TextView tvName = helper.getView(R.id.tvName);
                        ImageView ivHead = helper.getView(R.id.ivHead);
                        tvName.setText(UserInfo.getUserInfo().nickName);
                        ImageLoader.getInstance().load(activity, UserInfo.getUserInfo().backgroundImage, ivCover, new RequestOptions().centerCrop());
                        ImageLoader.getInstance().load(activity, UserInfo.getUserInfo().headImage, ivHead, new RequestOptions().transform(new RoundedCornersTransformation(AndroidUtil.dip2px(5))));
                        return;
                    }
                    final int position = poi - 1;
                    final ItemQuznZi item = allList.get(position);
                    View yearView = helper.getView(R.id.yearView);
                    TextView tvYear = helper.getView(R.id.tvYear);
                    View monthView = helper.getView(R.id.monthView);
                    TextView tvMonth = helper.getView(R.id.tvMonth);
                    TextView tvDay = helper.getView(R.id.tvDay);
                    TextView tvCity = helper.getView(R.id.tvCity);
                    ImageView ivCover = helper.getView(R.id.ivCover);
                    ImageView ivPlay = helper.getView(R.id.ivPlay);
                    TextView tvContent = helper.getView(R.id.tvContent);
                    View media = helper.getView(R.id.media);
                    int year = DateUtil.getYear(item.createTime);
                    int month = DateUtil.getMonth(item.createTime);
                    int day = DateUtil.getDay(item.createTime);

                    if (position == 0) {
                        yearView.setVisibility(View.GONE);
                        if (day == currentDay) {
                            monthView.setVisibility(View.GONE);
                        } else {
                            monthView.setVisibility(View.VISIBLE);
                        }
                    } else {
                        ItemQuznZi itemPre = allList.get(position - 1);
                        int yearPre = DateUtil.getYear(itemPre.createTime);
                        if (year == yearPre) {
                            yearView.setVisibility(View.GONE);
                        } else {
                            yearView.setVisibility(View.VISIBLE);
                        }
                        if (day == DateUtil.getDay(itemPre.createTime)) {
                            monthView.setVisibility(View.GONE);
                        } else {
                            monthView.setVisibility(View.VISIBLE);
                        }

                    }
                    tvYear.setText(year + "年");
                    tvMonth.setText(month + "月");
                    tvDay.setText(day + "日");
                    if (item.obj != null && item.obj.user != null) {
                        tvCity.setText(item.obj.user.cityName);
                    } else {
                        tvCity.setText("");
                    }
                    if (item.containsVideo == 1) {
                        String cover = ImageApi.getImage(item.videos);
                        ImageLoader.getInstance().load(activity, cover, ivCover);
                        media.setVisibility(View.VISIBLE);
                        ivPlay.setVisibility(View.VISIBLE);
                    } else if (item.containsImage == 1) {
                        String cover = ImageApi.getImage(item.images);
                        ImageLoader.getInstance().load(activity, cover, ivCover);
                        media.setVisibility(View.VISIBLE);
                        ivPlay.setVisibility(View.GONE);
                    } else {
                        media.setVisibility(View.GONE);
                    }
                    tvContent.setText(item.content);
                }
            };
            adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
//                    Intent intent = new Intent(activity, ZhaoFuWuLvYouViewActivity.class);
//                    intent.putExtra("lvYouTitle", "苹果6s");
//                    jump2Activity(intent);
                }
            });
            recycler.setAdapter(adapter);
        }
        adapter.notifyDataSetChanged();
    }


    private void loadData() {
        Map<String, Object> map = QuznZiHttp.getMap();
        map.put("containsImage", 1);
        map.put("containsVideo", 1);
        map.put("pageNumber", page);
        map.put("pageSize", pageSize);
        QuznZiHttp.list(map, new BaseEntityOb<PagerModel<ItemQuznZi>>() {
            @Override
            public void onDataDeal(boolean isSuccess, PagerModel<ItemQuznZi> data, String msg) {
                List<ItemQuznZi> list = null;
                if (isSuccess && data != null) {
                    list = data.content;
                }
                if (page == 1) {
                    allList.clear();
                }
                initAdapter(list);
                if (list != null && list.size() >= pageSize) {
                    proxyLayout.setCanLoadMore(true);
                } else {
                    proxyLayout.setCanLoadMore(false);
                }
                if (allList.isEmpty()) {
                    proxyLayout.showEmptyView();
                } else {
                    proxyLayout.showContentView();
                }
                proxyLayout.dragFinish();
            }
        });
    }

    private void praise(final ItemQuznZi item, final int position) {
        Map<String, Object> map = HttpUtils.getMap();
        map.put("id", item.id);
        map.put("type", 50);
        HttpUtils.praise(map, new BaseEntityOb<Integer>() {
            @Override
            public void onStart() {
                super.onStart();
                showDialog();
            }

            @Override
            public void onDataDeal(boolean isSuccess, Integer data, String msg) {
                hideDialog();
                showToast(msg);
                if (item.obj == null) {
                    item.obj = new ItemQuznZi.Extra();
                }
                item.obj.likeCount = data;
                adapter.notifyItemChanged(position);
            }
        });
    }

    private void comment(String data, final ItemQuznZi item, final int position) {
        Map<String, Object> map = HttpUtils.getMap();
        map.put("content", data);
        map.put("typeId", item.id);
        map.put("type", 50);
        HttpUtils.comment(map, new BaseEntityOb<Object>() {
            @Override
            public void onStart() {
                super.onStart();
                showDialog();
            }

            @Override
            public void onDataDeal(boolean isSuccess, Object data, String msg) {
                hideDialog();
                showToast(msg);
//                if (item.obj == null) {
//                    item.obj = new ItemQuznZi.Extra();
//                }
//                item.obj.likeCount = data;
//                adapter.notifyItemChanged(position);
            }
        });
    }
}